import { remoteLoad } from '@/assets/js/utils.js';
import { relativeTimeRounding } from 'moment';
export default {
  created() {
    this.loadMapScript();
  },
  data() {
    var checkSlotsNumber = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('停车场总车位数不能为空'));
      } else if (!Number.isInteger(value)) {
        callback(new Error('请输入整数值'));
      } else if (value < 0) {
        callback(new Error('不能小于0'));
      } else if (this.parkBaseInfo.tempCarports && value < this.parkBaseInfo.tempCarports) {
        callback(new Error('停车场总车位数不能小于停车场临停车位数'));
      } else {
        callback();
        // this.$refs.parkBaseInfo.validateField('tempCarports');
      }
    };

    var checkTempCarports = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('停车场临停车位数不能为空'));
      } else if (this.parkBaseInfo.slotsNumber && value > this.parkBaseInfo.slotsNumber) {
        callback(new Error('停车场临停车位数不能大于停车场总车位数'));
      } else {
        callback();
        // this.$refs.parkBaseInfo.validateField('slotsNumber');
      }
    };

    var checkMapVal = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('车场经纬度不能为空'));
      } else if (!value.split(',')[0] || !value.split(',')[1]) {
        callback(new Error('经纬度格式错误'));
      } else if (
        !(
          /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,6})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,6}|180)$/.test(
            value.split(',')[0]
          ) || !/^(\-|\+)?([0-8]?\d{1}\.\d{0,6}|90\.0{0,6}|[0-8]?\d{1}|90)$/.test(value.split(',')[1])
        )
      ) {
        callback(new Error('经纬度格式错误'));
      } else {
        callback();
        // this.$refs.parkBaseInfo.validateFsield('slotsNumber');
      }
    };

    const self = this;
    async function checkParkName(rule, value, callback) {
      if (value === '') {
        callback(new Error('停车场名称不能为空'));
      } else {
        const isVaid = await self.checkIsParkNameRepeat(value).catch(err => {
          callback(new Error(err));
        });
        if (!isVaid) {
          callback(new Error(''));
        } else {
          callback();
        }
      }
    }
    return {
      rules: {
        name: [{ required: true, validator: checkParkName, trigger: 'blur' }],
        picStr: [{ required: true, message: '请上传停车场图片', trigger: 'change' }],
        address: [{ required: true, message: '停车场详细地址不能为空', trigger: 'blur' }],
        'uiOpt.gpsXY': [{ required: true, validator: checkMapVal, trigger: 'blur' }],
        slotsNumber: [{ required: true, validator: checkSlotsNumber, trigger: 'blur' }],
        tempCarports: [{ required: true, validator: checkTempCarports, trigger: 'blur' }],
        parkingSupervisor: [{ required: true, message: '负责人姓名不能为空', trigger: 'blur' }],
        defaultProvince: [{ required: true, message: '不能为空', trigger: 'blur' }],
        parkingSupervisorPhone: [
          { required: true, message: '负责人手机号码不能为空', trigger: 'blur' },
          { pattern: /^1\d{10}$/, message: '手机号码格式错误', trigger: 'blur' }
        ],
        'uiOpt.areaSelected[0]': [{ required: true, message: '区域不能为空', trigger: 'change' }],
        'uiOpt.areaSelected[1]': [{ required: true, message: '区域不能为空', trigger: 'change' }],
        'uiOpt.areaSelected[2]': [{ required: true, message: '区域不能为空', trigger: 'change' }]
        // 'uiOpt.protocolKey': [{ required: true, message: '请上传停车场协议', trigger: 'blur' }]
      },
      mapUI_data: {
        MapKey: 'e8c0167da5b7c6e9c558b7c896afd406',
        markerSrc: require('../../../public/static/img/ic_map_destination.png'),
        markerSelectedSrc: require('../../../public/static/img/ic_map_pin_none_seleted@2x.png'),
        dialogVisible: false,
        map: null,
        curMapMarker: null,
        selectPos: { x: '', y: '' },
        autocompleteObj: null, //输入提示对象
        placeSearchObj: null //POI搜索对象
      }
    };
  },
  methods: {
    loadMapScript() {
      //载入高德地图API
      if (!(window.AMap && window.AMapUI)) {
        remoteLoad(
          `https://webapi.amap.com/maps?v=1.4.6&key=${this.mapUI_data.MapKey}&plugin=AMap.Autocomplete,AMap.PlaceSearch`
        );
        setTimeout(() => {
          remoteLoad('https://webapi.amap.com/ui/1.0/main.js');
        }, 1500);
      }
    },
    async initParkMap() {
      const self = this;
      const opt = await this.getLocationPos();
      if (!opt) return;

      this.mapUI_data.dialogVisible = true;
      this.$nextTick(() => {
        this.mapUI_data.map = new AMap.Map('park-map', Object.assign(opt, { resizeEnable: true }));
        //输入提示
        var autoOptions = {
          city: '',
          input: 'tipinput'
        };
        var auto = new AMap.Autocomplete(autoOptions);
        var placeSearch = new AMap.PlaceSearch({
          map: this.mapUI_data.map,
          showCover: false,
          renderStyle: 'newpc'
        }); //构造地点查询类
        AMap.event.addListener(auto, 'select', function(e) {
          placeSearch.setCity(e.poi.adcode);
          placeSearch.search(e.poi.name); //关键字查询查询
        });
        //注册监听，当选中某条记录时会触发
        AMap.event.addListener(placeSearch, 'markerClick', function(curmarker) {
          self.addMarker({
            x: curmarker.data.location.lng,
            y: curmarker.data.location.lat
          });
        });

        //如果经纬度有值,标注原来的坐标点
        let gpsXY = this.parkBaseInfo.uiOpt.gpsXY;
        const reg = /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,6})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,6}|180)$/;
        if (gpsXY && reg.test(gpsXY.split(',')[0]) && reg.test(gpsXY.split(',')[1])) {
          this.addMarker({
            x: gpsXY.split(',')[0],
            y: gpsXY.split(',')[1]
          });
        }

        this.mapUI_data.map.on('click', function(e) {
          self.addMarker({
            x: e.lnglat.getLng(),
            y: e.lnglat.getLat()
          });
        });
      });
    },
    addMarker(pos) {
      const self = this;
      this.mapUI_data.selectPos = {
        x: pos.x,
        y: pos.y
      };
      if (this.mapUI_data.curMapMarker !== null) {
        this.mapUI_data.map.remove(self.mapUI_data.curMapMarker);
        this.mapUI_data.curMapMarker = [];
      }

      AMapUI.loadUI(['overlay/SimpleMarker'], function(SimpleMarker) {
        let marker = new SimpleMarker({
          iconStyle: {
            src: self.mapUI_data.markerSrc,
            style: {
              width: '48px',
              height: '48px'
            }
          },
          //设置基点偏移
          offset: new AMap.Pixel(-24, -48),
          map: self.mapUI_data.map,
          showPositionPoint: false,
          position: [pos.x, pos.y],
          zIndex: 100,
          topWhenClick: true
        });
        self.mapUI_data.curMapMarker = [marker];
      });
    },
    setMapPos() {
      this.parkBaseInfo.uiOpt.gpsXY = `${this.mapUI_data.selectPos.x},${this.mapUI_data.selectPos.y}`;
      this.mapUI_data.map.destroy();
      this.mapUI_data.map = null;
      this.mapUI_data.selectPos = { x: '', y: '' };
      this.mapUI_data.dialogVisible = false;
      this.$refs.parkBaseInfo.validateField('uiOpt.gpsXY');
    },
    mapDailogHide() {
      this.mapUI_data.map.destroy();
      this.mapUI_data.map = null;
      this.mapUI_data.selectPos = { x: '', y: '' };
      this.mapUI_data.dialogVisible = false;
    },
    getLocationPos() {
      const self = this;
      const reg = /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,6})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,6}|180)$/;
      return new Promise((resolve, reject) => {
        //如果经纬度有值
        let gpsXY = self.parkBaseInfo.uiOpt.gpsXY;
        if (gpsXY && reg.test(gpsXY.split(',')[0]) && reg.test(gpsXY.split(',')[1])) {
          resolve({
            zoom: 17,
            center: [gpsXY.split(',')[0], gpsXY.split(',')[1]]
          });
        }
        //如果经纬度为空
        if (!self.parkBaseInfo.areaName) {
          self.showToast('请完整选择停车场区域再选取经纬度', 2, 2500);
          return;
        }

        let area = self.parkBaseInfo.areaName.split('-');
        AMap.plugin('AMap.Geocoder', function() {
          let geocoder = new AMap.Geocoder();
          let searchArea = area[1] === '市辖区' || area[1] === '市辖县' ? area[0] + area[2] : area.join('');
          geocoder.getLocation(searchArea, function(status, result) {
            if (status === 'complete' && result.info === 'OK') {
              resolve({
                zoom: 15,
                center: [result.geocodes[0].location.lng, result.geocodes[0].location.lat]
              });
            }
          });
        });
      });
    },
    setFixNumber() {
      if (
        this.parkBaseInfo.slotsNumber !== '' &&
        this.parkBaseInfo.tempCarports !== '' &&
        this.parkBaseInfo.slotsNumber >= this.parkBaseInfo.tempCarports
      ) {
        this.$set(this.parkBaseInfo, 'fixNumber', this.parkBaseInfo.slotsNumber - this.parkBaseInfo.tempCarports);
      }
    },
    getDefaultProvince(pkAreaId) {
      var provinceName = this.parkBaseInfo.uiOpt.areaAreaData[0].filter(item => {
        return item.pkAreaId === pkAreaId;
      })[0].localName;
      switch (provinceName) {
        case '北京市':
          return '京';
        case '天津市':
          return '津';
        case '重庆市':
          return '渝';
        case '上海市':
          return '沪';
        case '河北省':
          return '冀';
        case '山西':
          return '晋';
        case '辽宁省':
          return '辽';
        case '吉林省':
          return '吉';
        case '黑龙江省':
          return '黑';
        case '江苏省':
          return '苏';
        case '浙江':
          return '浙';
        case '安徽省':
          return '皖';
        case '福建省':
          return '闽';
        case '江西省':
          return '赣';
        case '山东省':
          return '鲁';
        case '河南省':
          return '豫';
        case '湖北省':
          return '鄂';
        case '湖南省':
          return '湘';
        case '广东':
          return '粤';
        case '海南省':
          return '琼';
        case '四川省':
          return '川';
        case '贵州省':
          return '贵';
        case '云南省':
          return '滇';
        case '陕西省':
          return '陕';
        case '甘肃省':
          return '甘';
        case '青海省':
          return '青';
        case '台湾':
          return '台';
        case '内蒙古自治区':
          return '蒙';
        case '广西壮族自治区':
          return '桂';
        case '宁夏回族自治区':
          return '宁';
        case '新疆维吾尔自治区':
          return '新';
        case '西藏自治区':
          return '藏';
        case '香港特别行政区':
          return '港';
        case '澳门特别行政区':
          return '澳';
      }
    },
    getAreaLv1() {
      API.fetchGet('/operatorPark/getAreaByFatherID', {
        fatherID: 0
      }).then(
        res => {
          if (res.data) {
            this.parkBaseInfo.uiOpt.areaAreaData.splice(0, 1, res.data);
          }
        },
        err => {}
      );
    },
    getAreaLv2(val) {
      this.parkBaseInfo.areaName = '';
      this.parkBaseInfo.uiOpt.defaultProvince = this.getDefaultProvince(val);
      this.parkBaseInfo.uiOpt.areaSelected.splice(0, 1, val);
      this.parkBaseInfo.uiOpt.areaSelected.splice(1, 1, '');
      this.parkBaseInfo.uiOpt.areaSelected.splice(2, 1, '');
      API.fetchGet('/operatorPark/getAreaByFatherID', {
        fatherID: val
      }).then(
        res => {
          if (res.data) {
            this.parkBaseInfo.uiOpt.areaAreaData.splice(1, 1, res.data);
            this.parkBaseInfo.uiOpt.areaAreaData.splice(2, 1, []);
          }
        },
        err => {}
      );
    },
    getAreaLv3(val) {
      this.parkBaseInfo.areaName = '';
      this.parkBaseInfo.uiOpt.areaSelected.splice(1, 1, val);
      this.parkBaseInfo.uiOpt.areaSelected.splice(2, 1, '');
      API.fetchGet('/operatorPark/getAreaByFatherID', {
        fatherID: val
      }).then(
        res => {
          if (res.data) {
            this.parkBaseInfo.uiOpt.areaAreaData.splice(2, 1, res.data);
          }
        },
        err => {}
      );
    },
    setParkBaseInfoAreaData(val) {
      const self = this;
      this.parkBaseInfo.uiOpt.areaSelected.splice(2, 1, val);
      this.parkBaseInfo.areaFullPath = this.parkBaseInfo.uiOpt.areaSelected.join('.');
      this.parkBaseInfo.areaID = val;
      let areaName = '';
      this.parkBaseInfo.uiOpt.areaSelected.forEach((item, index) => {
        const cur_item = self.parkBaseInfo.uiOpt.areaAreaData[index].filter(sitem => sitem.pkAreaId === item);
        if (index !== 2) {
          areaName += `${cur_item[0].localName}-`;
        } else {
          areaName += cur_item[0].localName;
        }
      });
      this.parkBaseInfo.areaName = areaName;
    }
  }
};
